package mine.code.day.year2021.month08;

import org.junit.Test;

/**
 * 给定一个整数 n，计算所有小于等于 n 的非负整数中数字 1 出现的个数。
 * <p>
 * 输入：n = 13
 * 输出：6
 *
 * @author caijinnan
 */
public class Day13_数字1的个数 {


    @Test
    public void run() {
        int n = 1;
        System.out.println(countDigitOne(n));
    }

    public int countDigitOne(int n) {
        int sum = 0;
        int bit = 1;
        int length = 0;
        for (int i = n; i >= 10; i /= 10) {
            length++;
            bit *= 10;
        }
        while (bit >= 1) {
            int bitNum = n / bit;
            int addNum = 0;
            if (bitNum != 0) {
                if (bitNum != 1) {
                    addNum = bitNum * bit / 10 * (length) + bit;
                } else {
                    addNum = bitNum * bit / 10 * (length) + 1 + n % bit;
                }
            }
            length--;
            sum += addNum;
            n %= bit;
            bit /= 10;
        }
        return sum;
    }
}
